import React, { useState } from "react";
import type { Dayjs } from "dayjs";
import { PickerPanel } from "rc-picker";
import { isNil } from "@ct0/functions";
import dayjs from "dayjs";
import localeCN from "rc-picker/es/locale/zh_CN";
import localeUS from "rc-picker/es/locale/en_US";
import generateConfig from "rc-picker/es/generate/dayjs";
import { createUseStyles } from "react-jss";
import classNames from "classnames";

interface Props {
  value?: number;
  onChange?: (value: number | null) => void;
  meta?: {
    isChinese?: boolean;
  };
}

export default function Datetime({
  value: propsValue,
  onChange,
  meta = {},
}: Props) {
  const [value, setValue] = useState(
    isNil(propsValue) ? undefined : dayjs(propsValue)
  );
  const { isChinese = true } = meta;
  const classes = useStyles();

  return (
    <div className={classNames("ct0-picker-dropdown", classes.wrap)}>
      <div className="ct0-picker-panel-container">
        <PickerPanel<Dayjs>
          prefixCls="ct0-picker"
          value={value}
          locale={isChinese ? localeCN : localeUS}
          generateConfig={generateConfig}
          onChange={(v) => setValue(v)}
          onOk={() => onChange?.(value ? value.valueOf() : null)}
          showTime
        />
      </div>
    </div>
  );
}

const useStyles = createUseStyles({
  wrap: {
    width: "440px",
  },
});
